﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;


using ESOL.Common.Entity;
using ESOL.Business.Pur;
using ESOL.Business.Chk;
using ESOL.WinUI.Pur;

namespace ESOL.WinUI.Qc
{
    public partial class frmMaintainIncomingQc : BaseForm.frmBaseDialogyMaintainForm
    {
        #region vars
        public string ActionType { set; get; }
        public QcIqcOrderEntity SelectedIqcOrder { set; get; }
        private PurPurchaseArrivedEntity mSelectedPurchaseArrived;
        private List<DataRow> listDeleteItemDetail = new List<DataRow>();
        private List<DataRow> listDeleteItem = new List<DataRow>();
        #endregion

        #region ctor
        public frmMaintainIncomingQc()
        {
            InitializeComponent();
        }
        #endregion

        #region functions
        private void Init()
        {
            if (ActionType.Equals("View"))
            {
                btnSave.Enabled = false;
                btnCancel.Enabled = true;
            }
            if (ActionType.Equals("New"))
            {
                txtArrivalOrder.Enabled = true;
            }
            if (ActionType.Equals("Modify"))
            {
                txtArrivalOrder.Enabled = false;
            }
        }
        private void BindComobox()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("name");
            dt.Columns.Add("value");
            dt.Rows.Add("全检", "0");
            dt.Rows.Add("抽检", "1");
            repositoryItemGridLookUpEdit1.DataSource = dt;
            repositoryItemGridLookUpEdit1.DisplayMember = "name";
            repositoryItemGridLookUpEdit1.ValueMember = "value";
        }
        private void SetField()
        {
            if (SelectedIqcOrder != null)
            {
                txtQcOrder.Text = SelectedIqcOrder.OrderCode;
                if (string.IsNullOrEmpty(SelectedIqcOrder.PurArrivedId) == true)
                    return;
                PurPurchaseArrivedEntity mPurchaseArrived = PurPurchaseArrivedBs.GetPurchaseArrivedByID(SelectedIqcOrder.PurArrivedId);
                if (mPurchaseArrived == null)
                    return;
                txtArrivalOrder.Text = mPurchaseArrived.ArrivedCode;
                //供应商栏位尚未填

                ///////////////////
                UICommon.UICommonFunctions.SetTextBoxPersonName(txtCreatedBy, SelectedIqcOrder.CreateBy);
                UICommon.UICommonFunctions.SetTextBoxDate(txtCreateDate, SelectedIqcOrder.CreateDate, "yyyy-MM-dd");
                UICommon.UICommonFunctions.SetTextBoxPersonName(txtLastModifiedBy, Common.CommonParameter.CurrentUser.PersonId);
                UICommon.UICommonFunctions.SetTextBoxDate(txtLastModifiedDate, DateTime.Today, "yyyy-MM-dd");
                txtRemark.Text = SelectedIqcOrder.Remark;
            }
        }
        private void BindGridProductDetail()
        {
            if (SelectedIqcOrder == null)
                return;
            DataTable dtIqcOrderItem = QcIqcOrderItemBs.GetDtIqcOrderItemByOrderID(SelectedIqcOrder.OrderId);
            dtIqcOrderItem.TableName = "dtIqcOrderItem";
            DataTable dtIqcOrderItemDetail = QcIqcOrderItemDetailBs.GetDtIqcOrderItemDetailByOrderID(SelectedIqcOrder.OrderId);
            dtIqcOrderItemDetail.TableName = "dtIqcOrderItemDetail";
            DataSet ds = new DataSet();
            ds.Tables.Add(dtIqcOrderItem.Copy());
            ds.Tables.Add(dtIqcOrderItemDetail.Copy());

            DataColumn KeyColumn = ds.Tables[0].Columns["ORDER_ITEM_ID"];         //主键
            DataColumn ForeignColumn = ds.Tables[1].Columns["ORDER_ITEM_ID"];    //外键
            ds.Relations.Add("不良明细", KeyColumn, ForeignColumn);     //从表的层次名
            ds.Tables[0].AcceptChanges();
            ds.Tables[1].AcceptChanges();
            gvProductDetail.DataSource = ds.Tables[0];
        }
        private void BindGridByArrivedOrder()
        {
            if (mSelectedPurchaseArrived == null)
            {
                return;
            }
            if (SelectedIqcOrder == null)
            {
                SelectedIqcOrder = new QcIqcOrderEntity();
                SelectedIqcOrder.OrderId = Guid.NewGuid().ToString();
                SelectedIqcOrder.PurArrivedId = mSelectedPurchaseArrived.ArrivedId;
                SelectedIqcOrder.Status = "STATUS01";
                SelectedIqcOrder.ResultTag = 0;
                SelectedIqcOrder.CreateBy = Common.CommonParameter.CurrentUser.PersonId;
                SelectedIqcOrder.CreateDate = DateTime.Now;
                SelectedIqcOrder.LastModifiedBy = Common.CommonParameter.CurrentUser.PersonId;
                SelectedIqcOrder.LastModifiedDate = DateTime.Now;
            }
            else
            {
                SelectedIqcOrder.PurArrivedId = mSelectedPurchaseArrived.ArrivedId;
                SelectedIqcOrder.ResultTag = 0;
                SelectedIqcOrder.LastModifiedBy = Common.CommonParameter.CurrentUser.PersonId;
                SelectedIqcOrder.LastModifiedDate = DateTime.Now;
            }
            DataTable dtIqcOrderItem = QcIqcOrderItemBs.GetDtIqcOrderItemByOrderID("");
            dtIqcOrderItem.TableName = "dtIqcOrderItem";
            DataTable dtIqcOrderItemDetail = QcIqcOrderItemDetailBs.GetDtIqcOrderItemDetailByOrderID("");
            dtIqcOrderItemDetail.TableName = "dtIqcOrderItemDetail";

            DataTable dt = PurPurchaseArrivedItemBs.GetDtAllByArrivedID(mSelectedPurchaseArrived.ArrivedId);
            if (dt.Rows.Count == 0)
            {
                return;
            }
            foreach (DataRow dr in dt.Rows)
            {
                DataRow drIqcOrderItem = dtIqcOrderItem.NewRow();
                drIqcOrderItem["ORDER_ITEM_ID"] = Guid.NewGuid().ToString();
                drIqcOrderItem["ORDER_ID"] = SelectedIqcOrder.OrderId;
                drIqcOrderItem["ARRIVED_ITEM_ID"] = dr["ARRIVED_ITEM_ID"];
                drIqcOrderItem["REV_QTY"] = dr["ARRIVED_QTY"];
                drIqcOrderItem["CHECKED_QTY"] = dr["ARRIVED_QTY"];
                drIqcOrderItem["NG_QTY"] = 0;
                drIqcOrderItem["CHECKING_FUNCTION"] = "0";
                drIqcOrderItem["REMARK"] = null;
                drIqcOrderItem["PRODUCT_NAME"] = dr["PRODUCT_NAME"];
                drIqcOrderItem["PRODUCT_CODE"] = dr["PRODUCT_CODE"];
                drIqcOrderItem["MATERIAL"] = dr["MATERIAL"];
                drIqcOrderItem["DESCRIPTION"] = dr["DESCRIPTION"];
                drIqcOrderItem["NG_RATE"] = 0;
                dtIqcOrderItem.Rows.Add(drIqcOrderItem);
            }
            DataSet ds = new DataSet();
            ds.Tables.Add(dtIqcOrderItem.Copy());
            ds.Tables.Add(dtIqcOrderItemDetail.Copy());

            DataColumn KeyColumn = ds.Tables[0].Columns["ORDER_ITEM_ID"];         //主键
            DataColumn ForeignColumn = ds.Tables[1].Columns["ORDER_ITEM_ID"];    //外键
            ds.Relations.Add("不良明细", KeyColumn, ForeignColumn);     //从表的层次名
            gvProductDetail.DataSource = ds.Tables[0];
        }
        private bool CheckData()
        {
            DataTable dtMain = (DataTable)gvProductDetail.DataSource;
            if (dtMain == null || dtMain.Rows.Count == 0)
            {
                MessageBox.Show("物料清单不可为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            DataTable dtDetail = dtMain.DataSet.Tables[1];
            if (dtDetail.Rows.Count > 0)
            {
                foreach (DataRow dr in dtDetail.Rows)
                {
                    if (string.IsNullOrEmpty(dr["QTY"].ToString()))
                    {
                        MessageBox.Show("不良数量不可为空！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return false;
                    }
                }
            }
            return true;
        }
        private bool Save()
        {
            if (CheckData() == false)
                return false;
            DataTable dtMain = (DataTable)gvProductDetail.DataSource;
            DataTable dtDetail = dtMain.DataSet.Tables[1];
            if (dtDetail.Rows.Count > 0)
            {
                SelectedIqcOrder.ResultTag = 1;
                SelectedIqcOrder.Status = "STATUS01";
            }
            else if (dtDetail.Rows.Count == 0)
            {
                SelectedIqcOrder.ResultTag = 0;
                SelectedIqcOrder.Status = "STATUS06";
            }
            QcIqcOrderBs.SaveIqcOrder(ActionType, SelectedIqcOrder, dtMain, dtDetail, listDeleteItem, listDeleteItemDetail);
            return true;
        }
        #endregion

        #region events
        private void frmIncomingQcMaintain_Load(object sender, EventArgs e)
        {
            Init();
            BindComobox();
            SetField();
            BindGridProductDetail();
        }
        private void txtArrivalOrder_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainPurchaseArrivedQuery frm = new frmMaintainPurchaseArrivedQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedPurchaseArrived != null)
            {
                mSelectedPurchaseArrived = frm.SelectedPurchaseArrived;
                txtArrivalOrder.Text = mSelectedPurchaseArrived.ArrivedCode;
                BindGridByArrivedOrder();
            }
        }
        private int nFocusedRowIndex = -1;
        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (e.FocusedRowHandle < 0)
                return;
            nFocusedRowIndex = e.FocusedRowHandle;
            cmsTool.Enabled = true;
            tsNew.Enabled = true;
            tsDel.Enabled = true;
        }
        private void tsNew_Click(object sender, EventArgs e)
        {
            DataTable dtIqcOrderItem = (DataTable)gvProductDetail.DataSource;
            DataTable dtIqcOrderItemDetail = dtIqcOrderItem.DataSet.Tables[1];
            DataRow dr = dtIqcOrderItemDetail.NewRow();
            dr["ORDER_ITEM_DETAIL_ID"] = Guid.NewGuid().ToString();
            dr["ORDER_ID"] = SelectedIqcOrder.OrderId;
            dr["ORDER_ITEM_ID"] = dtIqcOrderItem.Rows[nFocusedRowIndex]["ORDER_ITEM_ID"];
            dr["RESULT"] = 1;//不良
            dtIqcOrderItemDetail.Rows.Add(dr);
            gridView1.ExpandMasterRow(nFocusedRowIndex);
        }
        private void tsDel_Click(object sender, EventArgs e)
        {
            DataTable dtMain = (DataTable)gvProductDetail.DataSource;
            DataTable dtDetail = dtMain.DataSet.Tables[1];
            int SelectedMainHandle = -1;
            int SelectedDetailHandle = -1;
            SelectedMainHandle = gridView1.FocusedRowHandle;
            DevExpress.XtraGrid.Views.Grid.GridView aView = (DevExpress.XtraGrid.Views.Grid.GridView)gridView1.GetDetailView(this.gridView1.GetSelectedRows()[0], 0);
            SelectedDetailHandle = aView.GetSelectedRows()[0];
            if (SelectedDetailHandle >= 0)//仅仅删除选中的不良明细
            {
                if (ActionType.Equals("Modify"))
                {
                    listDeleteItemDetail.Add(dtDetail.Rows[SelectedDetailHandle]);
                }
                dtDetail.Rows.RemoveAt(SelectedDetailHandle);
            }
            else if (SelectedMainHandle >= 0)//删除物料以及其下所有明细
            {
                string sOrderItemID = dtMain.Rows[SelectedMainHandle]["ORDER_ITEM_ID"].ToString();
                DataRow[] arryDr = dtDetail.Select("ORDER_ITEM_ID='" + sOrderItemID + "'");
                if (arryDr.Length > 0)
                {
                    if (ActionType.Equals("Modify"))
                    {
                        listDeleteItemDetail.AddRange(arryDr);
                    }
                    foreach (DataRow dr in arryDr)
                    {
                        dtDetail.Rows.Remove(dr);
                    }
                }
                if (ActionType.Equals("Modify"))
                {
                    listDeleteItem.Add(dtMain.Rows[SelectedMainHandle]);
                }
                dtMain.Rows.RemoveAt(SelectedMainHandle);
            }
        }

        private void gridView1_MasterRowExpanded(object sender, DevExpress.XtraGrid.Views.Grid.CustomMasterRowEventArgs e)
        {
            DevExpress.XtraGrid.Views.Grid.GridView aView = (DevExpress.XtraGrid.Views.Grid.GridView)gridView1.GetDetailView(e.RowHandle, 0);
            if (aView != null)
            {
                aView.BestFitColumns();
                aView.Name = "不良明细";
                aView.Columns["QTY"].Caption = "数量";
                aView.Columns["QTY"].AppearanceHeader.ForeColor = Color.Red;
                aView.Columns["DESCRIPTION"].Caption = "描述";
                aView.Columns["NG_CODE"].Caption = "不良代码";
                aView.Columns["ADVICE"].Caption = "处理意见";
                if (aView.Columns.ColumnByFieldName("ORDER_ITEM_DETAIL_ID") != null)
                {
                    aView.Columns["ORDER_ITEM_DETAIL_ID"].VisibleIndex = -1;
                }
                if (aView.Columns.ColumnByFieldName("ORDER_ID") != null)
                {
                    aView.Columns["ORDER_ID"].VisibleIndex = -1;
                }
                if (aView.Columns.ColumnByFieldName("ORDER_ITEM_ID") != null)
                {
                    aView.Columns["ORDER_ITEM_ID"].VisibleIndex = -1;
                }
                if (aView.Columns.ColumnByFieldName("RESULT") != null)
                {
                    aView.Columns["RESULT"].VisibleIndex = -1;
                }

                aView.CellValueChanged += new DevExpress.XtraGrid.Views.Base.CellValueChangedEventHandler(aView_CellValueChanged);
                ////列绑定ButtonEdit
                //RepositoryItemButtonEdit btnWorkingPerson = new RepositoryItemButtonEdit();
                //gvTargetStations.RepositoryItems.Add(btnWorkingPerson);
                //aView.Columns["GROUP_PERSON_NAME"].ColumnEdit = btnWorkingPerson;
                //btnWorkingPerson.ButtonClick += new DevExpress.XtraEditors.Controls.ButtonPressedEventHandler(btnWorkingPerson_ButtonClick);
            }
        }

        private void aView_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (e.Column.FieldName.Equals("QTY") == false)
                return;
            DataTable dtMain = (DataTable)gvProductDetail.DataSource;
            string sItemID = dtMain.Rows[nFocusedRowIndex]["ORDER_ITEM_ID"].ToString();
            DataTable dtDetail = dtMain.DataSet.Tables[1];
            DataRow[] arryDr = dtDetail.Select("ORDER_ITEM_ID='" + sItemID + "'");
            decimal dNgTotalQty = 0;
            foreach (DataRow dr in arryDr)
            {
                if (string.IsNullOrEmpty(dr["QTY"].ToString()) == false)
                    dNgTotalQty += Convert.ToDecimal(dr["QTY"].ToString());
            }
            dtMain.Rows[nFocusedRowIndex]["NG_QTY"] = dNgTotalQty;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (Save())
            {
                MessageBox.Show("保存成功！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                DialogResult = DialogResult.OK;
                return;
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;
            this.Dispose();
        }
        #endregion
    }
}